package com.ym.paas.config;

import com.alibaba.fastjson.JSON;
import com.ym.paas.dto.Result;
import com.ym.paas.exception.ServiceException;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;
import java.io.InputStream;

/**
 * RestTemplate Error process
 *
 * @author zetor
 * @date 9.28
 */
public class RestTemplateErrorHandler implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        HttpStatus statusCode = response.getStatusCode();
        if (statusCode.value() == HttpStatus.ACCEPTED.value()) {
            InputStream input = response.getBody();
            String respBody = IOUtils.toString(input, "UTF-8");
            Result ret = JSON.parseObject(respBody, Result.class);
            throw new ServiceException(ret.getMessage());
        }
        return false;
    }

    @Override
    public void handleError(ClientHttpResponse response) {
    }
}
